﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Tools
{
    public partial class FileMd5 : Base
    {
        public FileMd5()
        {
            InitializeComponent();
            base.SetDefaultLocation();
        }

        private void btn1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            txt_file1.Text = this.openFileDialog1.FileName;

            var md5 = GetFileMd5(txt_file1.Text);
            txt_md51.Text = md5;

            JiSuan();
        }

        private void btn2_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            txt_file2.Text = this.openFileDialog1.FileName;

            var md5 = GetFileMd5(txt_file2.Text);
            txt_md52.Text = md5;

            JiSuan();
        }

        /// <summary>
        /// 计算结果
        /// </summary>
        private void JiSuan()
        {
            var result = "不相同";
            if (txt_md51.Text == txt_md52.Text)
            {
                result = "相同";
            }
            lb_result.Text = result;
        }


        #region 获取文件MD5值

        /// <summary>
        /// 获取文件MD5值
        /// </summary>
        /// <param name="fileName">文件绝对路径</param>
        /// <returns>MD5值</returns>
        public static string GetFileMd5(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
        #endregion
    }
}
